<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Graphic from '@arcgis/core/Graphic'

// 获取用户信息
const userStore = useUserStore()
const currentUserId = computed(() => userStore.userInfo?.id || '')

// 状态变量
const loading = ref(false)
const myBorrowedBikes = ref<any[]>([])
const selectedBike = ref<any>(null)
const showReportDialog = ref(false)
const showSuccessDialog = ref(false)
const successMessage = ref('')

// 报修表单
const reportForm = ref({
  maintenanceReason: '',
})

// 自行车图层
let bikeLayer: FeatureLayer | null = null

// 初始化
onMounted(() => {
  initBikeLayer()
  loadMyBorrowedBikes()
})

// 初始化自行车图层
const initBikeLayer = () => {
  bikeLayer = new FeatureLayer({
    url: 'https://services7.arcgis.com/rDRhdC4brwj3FLD5/arcgis/rest/services/cycleFeaturelayer/FeatureServer/0',
    outFields: ['*'],
  })
}

// 加载我借用的单车
const loadMyBorrowedBikes = async () => {
  if (!bikeLayer) return

  loading.value = true
  try {
    // 查询当前用户借用的单车
    const query = bikeLayer.createQuery()
    query.where = `CurrentUseUserId = '${currentUserId.value}' AND Status = '使用中'`
    query.outFields = ['*']
    query.returnGeometry = true

    const results = await bikeLayer.queryFeatures(query)
    myBorrowedBikes.value = results.features.map((feature) => ({
      ...feature.attributes,
      geometry: feature.geometry,
    }))
  } catch (error) {
    console.error('加载借用单车失败:', error)
    ElMessage.error('加载借用单车失败')
  } finally {
    loading.value = false
  }
}

// 打开报修对话框
const openReportDialog = (bike: any) => {
  selectedBike.value = bike
  reportForm.value.maintenanceReason = ''
  showReportDialog.value = true
}

// 提交报修
const submitReport = async () => {
  if (!bikeLayer || !selectedBike.value) {
    ElMessage.error('单车信息不完整')
    return
  }

  if (!reportForm.value.maintenanceReason.trim()) {
    ElMessage.warning('请输入故障原因')
    return
  }

  try {
    loading.value = true
    const bike = selectedBike.value

    // 准备更新的属性
    const attributes: any = {
      OBJECTID: bike.OBJECTID,
      Status: '维修中',
      MaintenanceStatus: '等待维修',
      MaintenanceReason: reportForm.value.maintenanceReason,
      CurrentUseUserId: '', // 清空使用者ID
      BorrowTime: '', // 清空借用时间
    }

    // 创建更新要素（不包含几何信息）
    const updateFeature = new Graphic({
      attributes: attributes
    })

    // 更新要素
    const results = await bikeLayer.applyEdits({
      updateFeatures: [updateFeature],
    })

    if (results.updateFeatureResults && results.updateFeatureResults.length > 0) {
      // 关闭报修对话框
      showReportDialog.value = false

      // 显示成功信息
      successMessage.value = `您已成功提交故障报修！\n单车ID: ${bike.BikeId}\n故障原因: ${reportForm.value.maintenanceReason}`
      showSuccessDialog.value = true

      // 刷新借用列表
      loadMyBorrowedBikes()
    } else {
      ElMessage.error('提交报修失败')
    }
  } catch (error) {
    console.error('提交报修时出错:', error)
    ElMessage.error('操作失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 关闭成功对话框
const closeSuccessDialog = () => {
  showSuccessDialog.value = false
}
</script>

<template>
  <div class="student-report">
    <el-card class="report-card">
      <template #header>
        <div class="card-header">
          <h2>故障报修</h2>
        </div>
      </template>

      <el-alert
        title="您可以为您正在使用的单车提交故障报修"
        type="info"
        :closable="false"
        show-icon
        class="info-alert"
      />

      <div class="borrowed-bikes-section">
        <h3>我借用的单车</h3>
        <el-divider />

        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="3" animated />
        </div>

        <el-empty
          v-else-if="myBorrowedBikes.length === 0"
          description="您当前没有借用任何单车"
        >
          <template #image>
            <el-icon class="empty-icon"><svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
              <path fill="currentColor" d="M512 896a384 384 0 1 0 0-768 384 384 0 0 0 0 768zm0 64a448 448 0 1 1 0-896 448 448 0 0 1 0 896z"></path>
              <path fill="currentColor" d="M480 256a32 32 0 0 1 32 32v256a32 32 0 0 1-64 0V288a32 32 0 0 1 32-32z"></path>
              <path fill="currentColor" d="M480 512h256a32 32 0 0 1 0 64H480a32 32 0 0 1 0-64z"></path>
            </svg></el-icon>
          </template>
        </el-empty>

        <div v-else class="bike-list">
          <el-card v-for="bike in myBorrowedBikes" :key="bike.BikeId" class="bike-item">
            <div class="bike-info">
              <div class="bike-header">
                <span class="bike-type">{{ bike.BikeType }}</span>
                <el-tag size="small" type="success">ID: {{ bike.BikeId }}</el-tag>
              </div>

              <div class="bike-details">
                <p><strong>当前地址:</strong> {{ bike.NowAddress }}</p>
                <p><strong>借用时间:</strong> {{ bike.BorrowTime }}</p>
                <p v-if="bike.BikeType === '电动单车'"><strong>电量:</strong> {{ bike.BatteryLevel }}</p>
              </div>

              <div class="bike-actions">
                <el-button type="warning" @click="openReportDialog(bike)">
                  <el-icon class="el-icon--left"><svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                    <path fill="currentColor" d="M512 64a448 448 0 1 1 0 896 448 448 0 0 1 0-896zm0 832a384 384 0 0 0 0-768 384 384 0 0 0 0 768zm48-176a48 48 0 1 1-96 0 48 48 0 0 1 96 0zm-48-464a32 32 0 0 1 32 32v288a32 32 0 0 1-64 0V288a32 32 0 0 1 32-32z"></path>
                  </svg></el-icon>
                  报修
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </el-card>

    <!-- 报修对话框 -->
    <el-dialog
      v-model="showReportDialog"
      title="提交故障报修"
      width="500px"
      destroy-on-close
    >
      <el-form :model="reportForm" label-position="top">
        <el-form-item label="单车信息">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="单车ID">{{ selectedBike?.BikeId }}</el-descriptions-item>
            <el-descriptions-item label="单车类型">{{ selectedBike?.BikeType }}</el-descriptions-item>
            <el-descriptions-item label="当前地址">{{ selectedBike?.NowAddress }}</el-descriptions-item>
          </el-descriptions>
        </el-form-item>

        <el-form-item label="故障原因" required>
          <el-input
            v-model="reportForm.maintenanceReason"
            type="textarea"
            :rows="4"
            placeholder="请详细描述单车故障情况，以便维修人员及时处理"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showReportDialog = false">取消</el-button>
          <el-button type="primary" @click="submitReport" :loading="loading">提交报修</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 操作成功提示对话框 -->
    <el-dialog
      v-model="showSuccessDialog"
      title="报修成功"
      width="30%"
      center
    >
      <div class="success-content">
        <el-icon class="success-icon" size="large" color="#67C23A">
          <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
            <path
              fill="currentColor"
              d="M512 64a448 448 0 1 1 0 896 448 448 0 0 1 0-896zm-55.808 536.384-99.52-99.584a38.4 38.4 0 1 0-54.336 54.336l126.72 126.72a38.272 38.272 0 0 0 54.336 0l262.4-262.464a38.4 38.4 0 1 0-54.272-54.336L456.192 600.384z"
            />
          </svg>
        </el-icon>
        <p class="success-message">{{ successMessage }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="closeSuccessDialog">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.student-report {
  padding: 20px;
}

.report-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.info-alert {
  margin-bottom: 20px;
}

.borrowed-bikes-section {
  margin-top: 20px;
}

.borrowed-bikes-section h3 {
  font-size: 18px;
  color: #303133;
  margin-bottom: 10px;
}

.loading-container {
  padding: 20px 0;
}

.bike-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.bike-item {
  border-radius: 8px;
  transition: all 0.3s;
}

.bike-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.bike-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.bike-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.bike-type {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}

.bike-details {
  font-size: 14px;
  color: #606266;
}

.bike-details p {
  margin: 5px 0;
}

.bike-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 8px;
}

.empty-icon {
  font-size: 60px;
  color: #909399;
}

.success-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.success-icon {
  font-size: 60px;
  margin-bottom: 20px;
}

.success-message {
  text-align: center;
  white-space: pre-line;
  color: #606266;
}
</style>
